package org.common4j2ee.stock.service.security;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.common4j2ee.stock.dao.user.UsersDaoImpl;
import org.common4j2ee.stock.entity.user.Authority;
import org.common4j2ee.stock.entity.user.Role;
import org.common4j2ee.stock.entity.user.Users;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;


/**
 * 实现SpringSecurity的UserDetailsService接口,实现获取用户Detail信息的回调函数.
 * 
 */
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService  {
	
	private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
	
	@Autowired
	private UsersDaoImpl usersDao;
	 	
	public UserDetails loadUserByUsername(String username)
			throws  DataAccessException {
			if (logger.isDebugEnabled()) {  
	            logger.debug("loadUserByUsername(String) - start"); //$NON-NLS-1$   
	        } 
			
			List<Users> userList=usersDao.findBy("loginName", username);
			
			if(userList==null||userList.size()<=0){
				String message = "用户"+username+"不存在";  
                logger.error(message);  
                throw new UsernameNotFoundException(message);  

			}
			
			Users user=userList.get(0);
			
			String password=user.getPassword();
			
			List<Role> roleList=user.getRoleList();
			
			if(roleList==null||roleList.size()<0){
				String message = "用户"+username+"未分配角色";  
                logger.error(message);  
                throw new UsernameNotFoundException(message);  

			}
			
			//List<GrantedAuthority> auths=new ArrayList<GrantedAuthority>();
			
			Map<String,GrantedAuthorityImpl> grantMap=new HashMap<String, GrantedAuthorityImpl>();
			
			for(Role item : roleList){  
                
                if (logger.isDebugEnabled()){  
                    logger.debug("用户：["+user.getLoginName()+"]拥有角色：["+item.getName()+"],即spring security中的access");  
                }  
                List<Authority> authList=item.getAuthorityList();
                if(authList!=null){
                	for(Authority auth:authList){
                		 if(!grantMap.containsKey(auth.getName())){
                			 GrantedAuthorityImpl grantedAuthorityImpl = new GrantedAuthorityImpl(auth.getName());
                			 grantMap.put(auth.getName(), grantedAuthorityImpl);
                		 }
                	}
                }
                
            }  

			org.springframework.security.core.userdetails.User rtUser=new User(username, password, true, true, true, true, grantMap.values());
	        
	        return rtUser;
	}

}

